package com.shop.front.service.pink;


import com.alibaba.fastjson.JSON;
import com.shop.front.response.FrontRetEnum;
import com.shop.front.service.pay.PayService;
import com.shop.front.service.store.StoreCartService;
import com.shop.front.service.store.StoreOrderService;
import com.shop.front.service.user.UserBillService;
import com.shop.front.vo.pink.PinkJishouVo;
import com.shop.front.vo.pink.StorePinkVo;
import com.shop.common.enums.pay.PayBusinessEnum;
import com.shop.common.enums.pay.PayStatusEnum;
import com.shop.common.enums.pay.PayTypeEnum;
import com.shop.common.enums.pink.JishouStatusEnum;
import com.shop.common.enums.pink.StorePinkRebateStatusEnum;
import com.shop.common.enums.pink.StorePinkStatusEnum;
import com.shop.common.enums.user.AccountTypeEnum;
import com.shop.common.enums.user.BillTableNameEnum;
import com.shop.common.enums.user.IncomeTypeEnum;
import com.shop.domain.pink.PinkJishou;
import com.shop.domain.pink.StorePink;
import com.shop.domain.pink.StorePinkConfig;
import com.shop.domain.pink.UserPinkInfo;
import com.shop.domain.store.StoreCart;
import com.shop.domain.user.User;
import com.shop.front.dao.pink.*;
import com.shop.front.dao.user.UserDao;
import com.shop.front.request.pink.*;
import com.shop.front.request.store.StoreCartAddReq;
import com.shop.front.request.store.StoreOrderCartInfoSubmitReq;
import com.shop.front.request.store.StoreOrderSubmitReq;
import com.shop.util.RandomUtil;
import com.shop.web.cache.RedisCache;
import com.shop.web.context.WebContext;
import com.shop.web.exception.AmountNotEnoughException;
import com.shop.web.exception.GCRuntimeException;
import com.shop.web.response.BaseResponse;
import com.shop.web.response.RetEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Transactional
public class StorePinkService {

    private static final Logger specialLog = LoggerFactory.getLogger("sys.special.log");

    @Autowired
    private UserPinkInfoDao userPinkInfoDao;
    @Autowired
    private PinkJishouDao pinkJishouDao;
    @Autowired
    private StorePinkDao storePinkDao;
    @Autowired
    private StorePinkConfigDao storePinkConfigDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private PinkJishouSQLDao pinkJishouSQLDao;
    @Autowired
    private StorePinkSQLDao storePinkSQLDao;
    @Autowired
    private UserBillService userBillService;
    @Autowired
    private PayService payService;
    @Autowired
    private StoreCartService storeCartService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private RedisCache redisCache;

    public BaseResponse pagePink(Long userId) {
        Page<StorePinkVo> page = storePinkSQLDao.pagePink(userId);
        return new BaseResponse(page);
    }

    public BaseResponse pagePinkHistory(Long userId) {
        Page<StorePinkVo> page = storePinkSQLDao.pagePinkHistory(userId);
        return new BaseResponse(page);
    }

    public BaseResponse pageJishou(Long userId) {
        Page<PinkJishouVo> page = pinkJishouSQLDao.pageJishou(userId);
        return new BaseResponse(page);
    }

    public BaseResponse pink(Long userId, UserPinkReq req) {
        Long pinkId = req.getPinkId();

        // 用户当前是否有正常拼团的记录
        int count = storePinkDao.countPinking(userId, pinkId);
        if(count >= 1) {
            return BaseResponse.fail("您已在该拼团中，请勿重复拼团！");
        }

        // 获取用户拼团信息
        UserPinkInfo userPinkInfo = userPinkInfoDao.findByPinkIdAndUserId(userId, pinkId);
        // 获取拼团配置信息
        StorePinkConfig pinkConfig = storePinkConfigDao.findSingle(pinkId);

        // 订单号
        String orderNo = RandomUtil.generateId7OrderNo("P", userId);

        StorePink pink = new StorePink();
        pink.setUid(userId);
        pink.setPinkId(pinkId);
        pink.setProductId(req.getProductId());
        pink.setProductAttrValueId(req.getProductAttrValueId());
        pink.setPrice(pinkConfig.getPrice());
        pink.setTotalPrice(pinkConfig.getPrice());
        pink.setOrderNo(orderNo);
        pink.setStorePinkNum(userPinkInfo.getPtNum());
        pink.setCreateTime(new Date());
        storePinkDao.save(pink);

        return new BaseResponse(pink);
    }

    public BaseResponse pinkOrderSubmit(Long userId, UserPinkOrderReq req) {
        Long storePinkId = req.getStorePinkId();

        // 付款类型校验
        PayTypeEnum payTypeEnum = PayTypeEnum.val(req.getPayCode());
        if(null == payTypeEnum) {
            return BaseResponse.fail("请选择支付方式！");
        }

        StorePink pink = storePinkDao.findSingle(storePinkId);
        if(StorePinkStatusEnum.NO_PAY.getKey() != pink.getStatus()) {
            return BaseResponse.fail("当前拼团记录不是待支付状态！");
        }

        // 修改订单信息
        storePinkDao.updateBySubmitOrder(pink.getId(), req.getUserAddressId(), payTypeEnum.getType(), payTypeEnum.getCode());

        // 创建付款订单
        BaseResponse resp = null;
        BigDecimal orderAmount = pink.getTotalPrice();
        User user = userDao.findSingle(userId);
        String orderNo = pink.getOrderNo();
        // 微信支付、支付宝支付
        if(PayTypeEnum.ALIPAY_JT == payTypeEnum || PayTypeEnum.WEIXIN_JT == payTypeEnum
                || PayTypeEnum.ALIPAY_SAND == payTypeEnum || PayTypeEnum.ALIPAY_SAND == payTypeEnum) {

            // 发起支付
            resp = payService.jtDoPay(PayBusinessEnum.STORE_PINK_ORDER, userId, pink.getId(),
                    orderAmount, pink.getOrderNo(), payTypeEnum);

        } else if(PayTypeEnum.YUE == payTypeEnum) {   // 余额支付

            // 扣除余额
            int subtractRows = userDao.subtractBalance(userId, orderAmount);
            if(subtractRows <= 0) {
                throw new AmountNotEnoughException(FrontRetEnum.USER_BALANCE_NOT_ENOUGH);
            }

            //更新之后金额
            BigDecimal refreshPrice = user.getBalance().subtract(orderAmount);

            //增加用户交易流水
            userBillService.addUserBill(userId, orderAmount, pink.getId(), BillTableNameEnum.PINK.getKey(), user.getBalance(),
                    refreshPrice, IncomeTypeEnum.EXPEND.getKey(), AccountTypeEnum.BALANCE.getKey(),
                    "参与拼团", "参与拼团，扣除余额" + orderAmount + "元");

            // 发起支付成功回调处理
            return this.cbPinkSubmit(pink.getId(), orderNo, PayStatusEnum.SUCCESS);

        } else if(PayTypeEnum.COIN == payTypeEnum) {   // TG支付

            // 扣除TG
            int subtractRows = userDao.subtractCoin(userId, orderAmount);
            if(subtractRows <= 0) {
                throw new AmountNotEnoughException(FrontRetEnum.USER_COIN_NOT_ENOUGH);
            }

            //更新之后金额
            BigDecimal refreshPrice = user.getCoin().subtract(orderAmount);

            //增加用户交易流水
            userBillService.addUserBill(userId, orderAmount, pink.getId(), BillTableNameEnum.PINK.getKey(), user.getCoin(),
                    refreshPrice, IncomeTypeEnum.EXPEND.getKey(), AccountTypeEnum.COIN.getKey(),
                    "参与拼团", "参与拼团，扣除TG" + orderAmount + "元");

            // 发起支付成功回调处理
            return this.cbPinkSubmit(pink.getId(), orderNo, PayStatusEnum.SUCCESS);


        } else {
            log.error("支付方式错误！payType -> " + JSON.toJSONString(payTypeEnum));
            throw new GCRuntimeException(FrontRetEnum.PAY_TYPE_IS_NOT_VALID);
        }

        return resp;
    }

    /**
     * 订单支付请求
     * @return
     */
    public BaseResponse checkPinkPayStatus(String orderNo) {
        StorePink pink = storePinkDao.findByOrderNo(orderNo);
        if(null == pink) {
            log.error("校验拼团订单支付状态，获取拼团订单信息为空！orderNo -> {}", orderNo);
            return new BaseResponse(FrontRetEnum.PAY_NO_NOT_EXISTS);
        }
        if(pink.getStatus() >= StorePinkStatusEnum.PINKING.getKey()) {  // 支付成功后的其他状态
            return new BaseResponse(pink);
        }

        return payService.jtCbPay(orderNo);
    }

    /**
     * 订单支付请求
     * @return
     */
    public BaseResponse cbPinkSubmit(Long id, String orderNo, PayStatusEnum payStatusEnum) {
        StorePink pink = storePinkDao.findSingle(id);
        if(null == pink) {
            log.error("拼团订单支付回调处理，获取拼团订单信息为空！id -> {}, orderNo -> {}", id, orderNo);
            return new BaseResponse(FrontRetEnum.PAY_NO_NOT_EXISTS);
        }

        // 根据支付状态修改订单状态
        if(PayStatusEnum.SUCCESS == payStatusEnum) {
            int rows = storePinkDao.updateStatusByPaySuccess(id, orderNo);
            if(rows <= 0) {
                return BaseResponse.ALREADY_EXECUTE;
            }

        } else {
            log.error("拼团订单支付回调处理，状态为非成功状态！id -> {}, orderNo -> {}, status -> {}", id, orderNo, payStatusEnum.getValue());
            return BaseResponse.fail("支付未成功");
        }
        return new BaseResponse(pink);
    }

    /**
     * 拼团转寄售
     * @param userId
     * @param userPinkToJishouReq
     * @return
     */
    public BaseResponse pinkTojishou(Long userId, UserPinkToJishouReq userPinkToJishouReq) {
        // 拼团记录
        StorePink storePink = storePinkDao.findSingle(userPinkToJishouReq.getStorePinkId());
        if(null == storePink) {
            return BaseResponse.fail("该拼团记录不存在！");
        }

        if(!storePink.getUid().equals(userId)){
            specialLog.info("~~~进入异常串值判断！~~~");
            specialLog.info("当前用户id -> {}", userId);
            specialLog.info("当前请求的用户信息 -> {}", JSON.toJSONString(WebContext.getPrincipal()));
            specialLog.info("当前请求request参数 -> {}", JSON.toJSONString(userPinkToJishouReq));
            specialLog.info("当前获取到的对象信息 -> {}", JSON.toJSONString(storePink));
            specialLog.info("当前请求的IP地址 -> {}", WebContext.getRequestIp());

            return BaseResponse.fail("操作失败，请稍后重试！");
        }

        if(StorePinkStatusEnum.WINING.getKey() != storePink.getStatus()) {
            return BaseResponse.fail("该拼团记录已处理！");
        }

        //通过pink_id获取拼团用户信息 判断用户是否可以寄售
        UserPinkInfo userPinkInfo = userPinkInfoDao.findByPinkIdAndUserId(userId,storePink.getPinkId());

        // 每5单一轮寄售，必须提货1单
        // 公式：本次至少提货数 = ((寄售中数 + 已寄售次数) + 提货次数 + 1) / 5 必须要小于 (提货次数 + 1)
        int jishouZhongNum = storePinkDao.countByUidAndStatus(userId, StorePinkStatusEnum.JISHOU_ZHONG.getKey());
        int jishouNum = userPinkInfo.getJishouNum() + jishouZhongNum;
        // 已提货次数
        int tihuoNum = userPinkInfo.getGetGoodsNum();
        // 本次至少提货数
        int needTihuoNum = (jishouNum + tihuoNum + 1) / 5;

        // 寄售次数是否超限
        if(needTihuoNum >= (tihuoNum + 1)) {  // 应提货数大于等于已提货数
            return BaseResponse.fail("寄售次数超限，请先提货！");
        }

        // 拼团转寄售缓存key
        int cacheTime = 5;  // 秒
        String cacheKey = "pinkTojishou_" + userId;
        // 缓存是否存在
        String cacheVal = redisCache.getString(cacheKey);
        if(StringUtils.isNotBlank(cacheVal)) {
            return BaseResponse.fail("当前操作正在队列中，请稍后重试！");
        } else {
            // 缓存请求
            redisCache.set(cacheKey, storePink.getId().toString(), cacheTime);
        }

        //添加寄售
        PinkJishou pinkJishou = new PinkJishou();
        pinkJishou.setPinkId(storePink.getPinkId());
        pinkJishou.setJishouMoney(storePink.getPrice());
        pinkJishou.setCreateTime(new Date());
        pinkJishou.setOrderNo(storePink.getOrderNo());
        pinkJishou.setProductId(storePink.getProductId());
        pinkJishou.setProductAttrValueId(storePink.getProductAttrValueId());
        pinkJishou.setUid(userId);
        pinkJishou.setStorePinkId(storePink.getId());
        pinkJishou.setUserAddressId(storePink.getUserAddressId());
        pinkJishouDao.save(pinkJishou);

        //修改拼团信息为寄售中
        int rows = storePinkDao.updateStorePinkStatusById(storePink.getId(), StorePinkStatusEnum.JISHOU_ZHONG.getKey(), StorePinkStatusEnum.WINING.getKey());
        if(rows <= 0) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            throw new GCRuntimeException(RetEnum.FAIL.getCode(), "拼团记录状态异常，寄售失败！");
        }

        // 正常结束，清除缓存
        redisCache.del(cacheKey);

        return new BaseResponse();
    }

    /**
     * 寄售转余额
     * @param userId
     * @param userPinkJishouToBalanceReq
     * @return
     */
    public BaseResponse jishouToUserBalance(Long userId, UserPinkJishouToBalanceReq userPinkJishouToBalanceReq) {
        // 拼团记录
        PinkJishou pinkJishou = pinkJishouDao.findSingle(userPinkJishouToBalanceReq.getPinkJishouId());
        if(null == pinkJishou) {
            return BaseResponse.fail("该寄售记录不存在！");
        }

        if(!pinkJishou.getUid().equals(userId)){
            specialLog.info("~~~进入异常串值判断！~~~");
            specialLog.info("当前用户id -> {}", userId);
            specialLog.info("当前请求的用户信息 -> {}", JSON.toJSONString(WebContext.getPrincipal()));
            specialLog.info("当前请求request参数 -> {}", JSON.toJSONString(userPinkJishouToBalanceReq));
            specialLog.info("当前获取到的对象信息 -> {}", JSON.toJSONString(pinkJishou));
            specialLog.info("当前请求的IP地址 -> {}", WebContext.getRequestIp());

            return BaseResponse.fail("操作失败，请稍后重试！");
        }

        if(!pinkJishou.getStatus().equals(JishouStatusEnum.INIT.getKey())){
            return BaseResponse.fail("该寄售记录已处理！");
        }

        // 拼团job处理中，不允许该业务执行
        if(StringUtils.isNotBlank(redisCache.getString("exeStorePinkIng" + pinkJishou.getPinkId()))) {
            return BaseResponse.fail("拼团进行中，请稍后重试~~~");
        }

        // 用户拼团信息
        UserPinkInfo userPinkInfo = userPinkInfoDao.findByPinkIdAndUserId(userId,pinkJishou.getPinkId());

        // 未提货过
        if(0 == userPinkInfo.getGetGoodsNum()) {
            return BaseResponse.fail("请至少先提货一单再进行兑换！");
        }

        //第一轮未达到五单 转余额提示
        if(userPinkInfo.getAllPzNum() < 5){
            return BaseResponse.fail("请在本轮中满五单后再兑换！");
        }

        // 兑换是否超限
        // 可兑换 = 寄售成功次数 / 4 < 中奖次数 / 5
        if(userPinkInfo.getJishouNum() / 4 >= userPinkInfo.getAllPzNum() / 5) {
            return BaseResponse.fail("可兑换次数超限！");
        }

        // 兑换是否超限
        // 本次最少提货数 = ((寄售中数 + 已寄售次数) + 提货次数 + 1) / 5 必须要小于等于 提货次数
        int jishouZhongNum = storePinkDao.countByUidAndStatus(userId, StorePinkStatusEnum.JISHOU_ZHONG.getKey());
        int jishouNum = userPinkInfo.getJishouNum();
        int tihuoNum = userPinkInfo.getGetGoodsNum();
        int jishouAllNum = jishouNum + jishouZhongNum;
        // 已提货次数
        // 本次最少提货数
        int minTihuoNum = (jishouAllNum + tihuoNum + 1) / 5;
        // 兑换是否超限
        if(minTihuoNum >= tihuoNum) {
            // 当寄售中数量超过了寄售成功的数量，需要重新判断寄售成功数与提货数的值
            // 最小提货次数 = 寄售成功次数 + 1 / 5
            minTihuoNum = (jishouNum + 1) / 5;
            if(minTihuoNum > tihuoNum) {
                return BaseResponse.fail("可兑换次数已超限！");
            }

            // 限制提货1次，则只能寄售成功对应的4的倍数
            // 最小提货次数 = 寄售成功次数 / 4
            minTihuoNum = jishouNum / 4;
            if(minTihuoNum >= tihuoNum) {
                return BaseResponse.fail("可兑换次数已超限。");
            }
        }

        // 防止提货次数过多
        // 最大兑换次数 = （寄售中数 + 已寄售数 + 提货数） / 5 * 4
        int maxToBalanceNum = (jishouAllNum + tihuoNum) / 5 * 4;
        if(maxToBalanceNum <= jishouNum) {
            return BaseResponse.fail("超出可兑换次数，请先寄售！");
        }

        // 寄售转余额缓存key
        int cacheTime = 5;  // 秒
        String cacheKey = "jishouToUserBalance_" + userId;
        // 缓存是否存在
        String cacheVal = redisCache.getString(cacheKey);
        if(StringUtils.isNotBlank(cacheVal)) {
            return BaseResponse.fail("当前操作正在队列中，请稍后重试！");
        } else {
            // 缓存请求
            redisCache.set(cacheKey, pinkJishou.getId().toString(), cacheTime);
        }

        //修改寄售状态
        int rows = pinkJishouDao.updateJishouStatus(userPinkJishouToBalanceReq.getPinkJishouId(), JishouStatusEnum.FINISH.getKey(), JishouStatusEnum.INIT.getKey());
        if(rows <= 0) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            throw new GCRuntimeException(RetEnum.FAIL.getCode(), "寄售记录状态异常，转余额失败！");
        }

        // 修改拼团状态为寄售成功
        storePinkDao.updateByJishouSuccess(pinkJishou.getStorePinkId());

        //用户拼团信息增加寄售成功转余额次数
        userPinkInfoDao.updateByJishouSuccess(userPinkInfo.getId());

        //用户寄售成功 增加余额
        User user = userDao.findSingle(userId);
        userDao.addBalance(userPinkInfo.getUid(),pinkJishou.getJishouMoney());

        //更新之后金额
        BigDecimal refreshPrice = user.getBalance().add(pinkJishou.getJishouMoney());
        //增加用户佣金流水
        userBillService.addUserBill(userId,pinkJishou.getJishouMoney(),pinkJishou.getId(), BillTableNameEnum.JISHOUTOBILL.getKey(),user.getBalance(),
                refreshPrice, IncomeTypeEnum.INCOME.getKey(), AccountTypeEnum.BALANCE.getKey(),
                "寄售成功", "寄售成功，添加余额" + pinkJishou.getJishouMoney() + "元");

        // 正常结束，清除缓存
        redisCache.del(cacheKey);

        return new BaseResponse();
    }


    /**
     * 拼中商品 提货
     * @param userId
     * @param req
     * @return
     */
    public BaseResponse pinkGetGoods(Long userId, UserPinkGetGoodsReq req) {
        // 获取拼团信息
        StorePink pink = storePinkDao.findSingle(req.getStorePinkId());
        if(null == pink) {
            return BaseResponse.fail("该拼团记录不存在");
        }

        if(!pink.getUid().equals(userId)){
            specialLog.info("~~~进入异常串值判断！~~~");
            specialLog.info("当前用户id -> {}", userId);
            specialLog.info("当前请求的用户信息 -> {}", JSON.toJSONString(WebContext.getPrincipal()));
            specialLog.info("当前请求request参数 -> {}", JSON.toJSONString(req));
            specialLog.info("当前获取到的对象信息 -> {}", JSON.toJSONString(pink));
            specialLog.info("当前请求的IP地址 -> {}", WebContext.getRequestIp());

            return BaseResponse.fail("操作失败，请稍后重试！");
        }

        if(StorePinkStatusEnum.WINING.getKey() != pink.getStatus()) {
            return BaseResponse.fail("该拼团记录已处理！");
        }

        // 拼团转提货缓存key
        int cacheTime = 5;  // 秒
        String cacheKey = "pinkGetGoods_" + userId;
        // 缓存是否存在
        String cacheVal = redisCache.getString(cacheKey);
        if(StringUtils.isNotBlank(cacheVal)) {
            return BaseResponse.fail("当前操作正在队列中，请稍后重试！");
        } else {
            // 缓存请求
            redisCache.set(cacheKey, pink.getId().toString(), cacheTime);
        }

        // 添加购物车逻辑
        StoreCartAddReq cartAddReq = new StoreCartAddReq();
        cartAddReq.setStorePink(pink);
        cartAddReq.setCartNum(1);
        cartAddReq.setProductId(pink.getProductId());
        cartAddReq.setProductAttrValueId(pink.getProductAttrValueId());
        BaseResponse resp = storeCartService.add(userId, cartAddReq);
        if(!resp.success()) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            return resp;
        }

        // 购物车信息
        StoreCart storeCart = (StoreCart) resp.getContent();

        List<StoreOrderCartInfoSubmitReq> cartInfoList = new ArrayList<>();
        StoreOrderCartInfoSubmitReq orderCartInfoSubmitReq = new StoreOrderCartInfoSubmitReq();
        orderCartInfoSubmitReq.setCartNum(1);
        orderCartInfoSubmitReq.setSign(storeCart.getSign());
        cartInfoList.add(orderCartInfoSubmitReq);

        // 添加订单逻辑
        StoreOrderSubmitReq orderSubmitReq = new StoreOrderSubmitReq();
        orderSubmitReq.setStorePink(pink);
        orderSubmitReq.setCartInfoList(cartInfoList);
        orderSubmitReq.setPayCode(pink.getPayCode());
        orderSubmitReq.setRealName(req.getRealName());
        orderSubmitReq.setUserPhone(req.getUserPhone());
        orderSubmitReq.setUserAddress(req.getUserAddress());
        orderSubmitReq.setUserAddressId(req.getUserAddressId());
        resp = storeOrderService.submit(userId, orderSubmitReq);
        if(!resp.success()) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            return resp;
        }

        // 修改状态为已提货
        int rows = storePinkDao.updateByGetGoods(pink.getId(), StorePinkStatusEnum.WINING.getKey());
        if(rows <= 0) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            throw new GCRuntimeException(RetEnum.FAIL.getCode(), "拼团记录状态异常，转提货失败！");
        }

        // 用户拼团信息增加提货成功次数
        userPinkInfoDao.updateByGetGoods(userId, pink.getPinkId());

        // 正常结束，清除缓存
        redisCache.del(cacheKey);

        return new BaseResponse();
    }

    /**
     * 寄售改商品提货
     * @param userId
     * @param req
     * @return
     */
    public BaseResponse jishouGetGoods(Long userId, UserPinkJishouGetGoodsReq req) {
        // 获取寄售记录
        PinkJishou pinkJishou = pinkJishouDao.findSingle(req.getPinkJishouId());
        if(null == pinkJishou) {
            return BaseResponse.fail("该寄售记录不存在");
        }

        if(!pinkJishou.getUid().equals(userId)){
            specialLog.info("~~~进入异常串值判断！~~~");
            specialLog.info("当前用户id -> {}", userId);
            specialLog.info("当前请求的用户信息 -> {}", JSON.toJSONString(WebContext.getPrincipal()));
            specialLog.info("当前请求request参数 -> {}", JSON.toJSONString(req));
            specialLog.info("当前获取到的对象信息 -> {}", JSON.toJSONString(pinkJishou));
            specialLog.info("当前请求的IP地址 -> {}", WebContext.getRequestIp());

            return BaseResponse.fail("操作失败，请稍后重试！");
        }

        if(JishouStatusEnum.INIT.getKey() != pinkJishou.getStatus()) {
            return BaseResponse.fail("该寄售记录已处理！");
        }

        // 寄售转提货缓存key
        int cacheTime = 5;  // 秒
        String cacheKey = "jishouGetGoods_" + userId;
        // 缓存是否存在
        String cacheVal = redisCache.getString(cacheKey);
        if(StringUtils.isNotBlank(cacheVal)) {
            return BaseResponse.fail("当前操作正在队列中，请稍后重试！");
        } else {
            // 缓存请求
            redisCache.set(cacheKey, pinkJishou.getId().toString(), cacheTime);
        }

        // 获取拼团信息
        StorePink pink = storePinkDao.findSingle(pinkJishou.getStorePinkId());

        // 添加购物车逻辑
        StoreCartAddReq cartAddReq = new StoreCartAddReq();
        cartAddReq.setStorePink(pink);
        cartAddReq.setCartNum(1);
        cartAddReq.setProductId(pink.getProductId());
        cartAddReq.setProductAttrValueId(pink.getProductAttrValueId());
        BaseResponse resp = storeCartService.add(userId, cartAddReq);
        if(!resp.success()) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            return resp;
        }

        // 购物车信息
        StoreCart storeCart = (StoreCart) resp.getContent();

        List<StoreOrderCartInfoSubmitReq> cartInfoList = new ArrayList<>();
        StoreOrderCartInfoSubmitReq orderCartInfoSubmitReq = new StoreOrderCartInfoSubmitReq();
        orderCartInfoSubmitReq.setCartNum(1);
        orderCartInfoSubmitReq.setSign(storeCart.getSign());
        cartInfoList.add(orderCartInfoSubmitReq);

        // 添加订单逻辑
        StoreOrderSubmitReq orderSubmitReq = new StoreOrderSubmitReq();
        orderSubmitReq.setStorePink(pink);
        orderSubmitReq.setCartInfoList(cartInfoList);
        orderSubmitReq.setPayCode(pink.getPayCode());
        orderSubmitReq.setRealName(req.getRealName());
        orderSubmitReq.setUserPhone(req.getUserPhone());
        orderSubmitReq.setUserAddress(req.getUserAddress());
        orderSubmitReq.setUserAddressId(req.getUserAddressId());
        resp = storeOrderService.submit(userId, orderSubmitReq);
        if(!resp.success()) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            return resp;
        }

        // 寄售状态改为
        int rows = pinkJishouDao.updateJishouStatus(req.getPinkJishouId(), JishouStatusEnum.CHANGE_GET_GOOD.getKey(), JishouStatusEnum.INIT.getKey());
        if(rows <= 0) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            throw new GCRuntimeException(RetEnum.FAIL.getCode(), "寄售记录状态异常，转提货失败！");
        }

        // 拼团状态记录状态
        rows = storePinkDao.updateByGetGoods(pink.getId(), StorePinkStatusEnum.JISHOU_ZHONG.getKey());
        if(rows <= 0) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            throw new GCRuntimeException(RetEnum.FAIL.getCode(), "寄售记录状态异常，拼团记录转提货失败！");
        }

        // 用户拼团信息增加提货成功次数
        userPinkInfoDao.updateByGetGoods(userId, pink.getPinkId());

        // 正常结束，清除缓存
        redisCache.del(cacheKey);

        return new BaseResponse();
    }

    public BaseResponse userPinkInfo(Long userId,Long pinkId) {
        return new BaseResponse(userPinkInfoDao.findByPinkIdAndUserId(userId,pinkId));
    }

    /**
     * 取消拼团
     * @param userId
     * @param storePinkId
     * @return
     */
    public BaseResponse cancelStorePink(Long userId, Long storePinkId){
        StorePink storePink = storePinkDao.findSingle(storePinkId);
        if(null == storePink) {
            return BaseResponse.fail("此拼团记录不存在！");
        }

        if(!storePink.getUid().equals(userId)){
            specialLog.info("~~~进入异常串值判断！~~~");
            specialLog.info("当前用户id -> {}", userId);
            specialLog.info("当前请求的用户信息 -> {}", JSON.toJSONString(WebContext.getPrincipal()));
            specialLog.info("当前请求request参数 -> {}", storePinkId);
            specialLog.info("当前获取到的对象信息 -> {}", JSON.toJSONString(storePink));
            specialLog.info("当前请求的IP地址 -> {}", WebContext.getRequestIp());

            return BaseResponse.fail("操作失败，请稍后重试！");
        }


        if(StorePinkStatusEnum.PINKING.getKey() != storePink.getStatus()) {
            return BaseResponse.fail("该拼团记录不能取消！");
        }

        // 拼团job处理中，不允许该业务执行
        if(StringUtils.isNotBlank(redisCache.getString("exeStorePinkIng"+storePink.getPinkId()))) {
            return BaseResponse.fail("拼团进行中，请稍后重试...");
        }

        // 取消拼团缓存key
        int cacheTime = 5;  // 秒
        String cacheKey = "cancelStorePink_" + userId;
        // 缓存是否存在
        String cacheVal = redisCache.getString(cacheKey);
        if(StringUtils.isNotBlank(cacheVal)) {
            return BaseResponse.fail("当前操作正在队列中，请稍后重试！");
        } else {
            // 缓存请求
            redisCache.set(cacheKey, storePink.getId().toString(), cacheTime);
        }

        //修改拼团订单已取消  结算状态为待结算
        int rows = storePinkDao.updateStorePinkStatusAndRebateStatusById(storePinkId,StorePinkStatusEnum.CANCEL.getKey(), StorePinkRebateStatusEnum.INIT.getKey(),
                        StorePinkStatusEnum.PINKING.getKey());
        if(rows <= 0) {
            // 错误拦截，清除缓存
            redisCache.del(cacheKey);

            throw new GCRuntimeException(RetEnum.FAIL.getCode(), "拼团记录状态异常，取消拼团失败！");
        }

        //用户寄售成功 增加余额
        User user = userDao.findSingle(userId);
        userDao.addBalance(user.getId(),storePink.getTotalPrice());

        //更新之后金额
        BigDecimal refreshPrice = user.getBalance().add(storePink.getTotalPrice());
        //增加用户佣金流水
        userBillService.addUserBill(userId,storePink.getTotalPrice(),storePink.getId(), BillTableNameEnum.CANCAL_STORE_PINK.getKey(),user.getBalance(),
                refreshPrice, IncomeTypeEnum.INCOME.getKey(), AccountTypeEnum.BALANCE.getKey(),
                "取消拼团", "取消拼团成功，添加余额" + storePink.getTotalPrice() + "元");

        // 正常结束，清除缓存
        redisCache.del(cacheKey);

        return new BaseResponse();
    }


    public BaseResponse updateStorePinkConfig(Long userId,Long pinkId,Long productId,Long productAttrValueId, Long userAddressId, int isAutoPt){

        userPinkInfoDao.updateStorePinkConfig(userId,pinkId, productId, productAttrValueId, userAddressId, isAutoPt);

        return new BaseResponse();
    }

/*

    public static void main(String[] args) {
        // 兑换是否超限
        // 本次最少提货数 = ((寄售中数 + 已寄售次数) + 提货次数 + 1) / 5 必须要小于等于 提货次数
        int jishouZhongNum = 4;
        int jishouNum = 8;
        int tihuoNum = 3;
        int jishouAllNum = jishouNum + jishouZhongNum;
        // 已提货次数
        // 本次最少提货数
        int minTihuoNum = (jishouAllNum + tihuoNum + 1) / 5;
        // 兑换是否超限
        if(minTihuoNum >= tihuoNum) {
            // 当寄售中数量超过了寄售成功的数量，需要重新判断寄售成功数与提货数的值
            // 最小提货次数 = 寄售成功次数 + 1 / 5
            minTihuoNum = (jishouNum + 1) / 5;
            if(minTihuoNum > tihuoNum) {
                System.out.println("可兑换次数已超限，请先提货！");
                return;
            }

            // 限制提货1次，则只能寄售成功对应的4的倍数
            // 最小提货次数 = 寄售成功次数 / 4
            minTihuoNum = jishouNum / 4;
            if(minTihuoNum >= tihuoNum) {
                System.out.println("可兑换次数已超限，请先提货。");
                return;
            }

            //return BaseResponse.fail("可兑换次数超限，请先提货！");
        }

        // 防止提货次数过多
        // 最大兑换次数 = （寄售中数 + 已寄售数 + 提货数） / 5 * 4
        int maxToBalanceNum = (jishouAllNum + tihuoNum) / 5 * 4;
        if(maxToBalanceNum <= jishouNum) {
            System.out.println("超出可兑换次数，请先寄售！");
            return;
        }

        System.out.println("OK");

    }
*/

}
